package config

import (
	"encoding/json"
	"os"
	"regexp"
	"shyxy-net/common/application"
	"shyxy-net/common/consul"
)

type Config struct {
	ApplicationConfig *application.Config `json:"application"`
	ConsulConfig      *consul.Config      `json:"consul"`

	Debug            bool   `json:"debug"`
	CORS             bool   `json:"cors"`
	CSRF             bool   `json:"csrf"`
	CORSAllowOrigins string `json:"cors_allow_origins"`
	MachineTag       string `json:"machine_tag"`

	ApiKeys []string `json:"api_keys"`

	OpaqueErrors                       bool             `json:"opaque_errors"`
	UseSubtleKeyComparison             bool             `json:"use_subtle_key_comparison"`
	DisableApiKeyRequirementForHttpGet bool             `json:"disable_api_key_requirement_for_http_get"`
	HttpGetExemptedEndpoints           []*regexp.Regexp `json:"http_get_exempted_endpoints"`
}

func Loading(configPath string) (*Config, error) {
	var cfg Config
	var err error
	if _, err = os.Stat(configPath); err != nil {
		return nil, err
	}
	file, err := os.Open(configPath)
	if err != nil {
		return nil, err
	}
	decoder := json.NewDecoder(file)
	if err = decoder.Decode(&cfg); err != nil {
		return nil, err
	}
	file.Close()
	return &cfg, nil
}
